<template>
  <div class="go-chart-linkage-setting">
    <n-alert type="info" title="联动控件">
      这里可以配置当前控件与其他组件的数据联动，支持数据筛选和组件属性控制。
    </n-alert>
    
    <!-- 联动类型选择 -->
    <n-space vertical :size="16" style="margin-top: 16px">
      <n-card size="small" title="联动类型">
        <n-radio-group v-model:value="linkageType" name="linkageType">
          <n-space>
            <n-radio value="filter">数据筛选联动</n-radio>
            <n-radio value="property">组件属性联动</n-radio>
          </n-space>
        </n-radio-group>
      </n-card>
      
      <n-button type="primary" @click="addLinkage">新增联动</n-button>
      
      <n-card
        v-for="(item, index) in linkageList"
        :key="index"
        class="n-card-shallow"
        size="small"
      >
        <n-space justify="space-between">
          <n-text>联动配置 - {{ index + 1 }}</n-text>
          <n-button type="error" text size="small" @click="removeLinkage(index)">
            <template #icon>
              <n-icon>
                <close-icon />
              </n-icon>
            </template>
          </n-button>
        </n-space>
        
        <n-divider style="margin: 10px 0" />
        
        <!-- 目标组件选择 -->
        <setting-item-box name="目标组件" :alone="true">
          <n-select
            v-model:value="item.targetId"
            :options="componentOptions"
            label-field="title"
            value-field="id"
            filterable
            placeholder="请选择目标组件"
            size="small"
            @update:value="() => updateFieldOptions(item, index)"
          />
        </setting-item-box>
        
        <!-- 数据筛选联动 -->
        <template v-if="linkageType === 'filter'">
          <setting-item-box name="筛选字段" :alone="true">
            <n-select
              v-model:value="item.filterField"
              :options="getFilterFieldOptions(item.targetId)"
              filterable
              placeholder="请选择筛选字段"
              size="small"
            />
          </setting-item-box>
          
          <setting-item-box name="筛选条件" :alone="true">
            <n-select
              v-model:value="item.condition"
              :options="filterConditionOptions"
              placeholder="请选择筛选条件"
              size="small"
            />
          </setting-item-box>
          
          <setting-item-box name="筛选值" :alone="true">
            <n-input 
              v-model:value="item.filterValue" 
              placeholder="请输入筛选值" 
              size="small" 
            />
          </setting-item-box>
        </template>
        
        <!-- 组件属性联动 -->
        <template v-if="linkageType === 'property'">
          <setting-item-box name="目标属性" :alone="true">
            <n-select
              v-model:value="item.propertyPath"
              :options="getPropertyOptions(item.targetId)"
              filterable
              placeholder="请选择目标属性"
              size="small"
            />
          </setting-item-box>
          
          <setting-item-box name="属性值" :alone="true">
            <n-input 
              v-model:value="item.propertyValue" 
              placeholder="请输入属性值" 
              size="small" 
            />
          </setting-item-box>
        </template>
        
        <!-- 联动触发条件 -->
        <setting-item-box name="触发条件" :alone="true">
          <n-select
            v-model:value="item.triggerCondition"
            :options="triggerConditionOptions"
            placeholder="请选择触发条件"
            size="small"
          />
        </setting-item-box>
        
        <setting-item-box name="触发值" :alone="true">
          <n-input 
            v-model:value="item.triggerValue" 
            placeholder="请输入触发值" 
            size="small" 
          />
        </setting-item-box>
      </n-card>
    </n-space>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useTargetData } from '../hooks/useTargetData.hook'
import { NButton, NCard, NSpace, NSelect, NInput, NAlert, NDivider, NIcon, NText, NRadioGroup, NRadio } from 'naive-ui'
import { Close as CloseIcon } from '@vicons/ionicons5'
import { SettingItemBox } from '@/components/Pages/ChartItemSetting'

const { chartEditStore, targetData } = useTargetData()

// 联动类型
const linkageType = ref<'filter' | 'property'>('filter')

// 联动配置列表
const linkageList = ref<any[]>([])

// 新增联动
const addLinkage = () => {
  linkageList.value.push({
    targetId: undefined,
    filterField: undefined,
    condition: undefined,
    filterValue: '',
    propertyPath: undefined,
    propertyValue: '',
    triggerCondition: 'eq',
    triggerValue: ''
  })
}

// 删除联动
const removeLinkage = (index: number) => {
  linkageList.value.splice(index, 1)
}

// 更新字段选项
const updateFieldOptions = (item: any, index: number) => {
  // 重置相关字段
  item.filterField = undefined
  item.propertyPath = undefined
}

// 获取所有可联动的组件（排除自己）
const componentOptions = computed(() => {
  return chartEditStore.getComponentList
    .filter(item => item.id !== targetData.value.id)
    .map(item => ({
      id: item.id,
      title: item.chartConfig?.title || item.id
    }))
})

// 获取筛选字段选项
const getFilterFieldOptions = (targetId: string) => {
  const target = chartEditStore.getComponentList.find(item => item.id === targetId)
  if (!target || !target.option?.dataset?.source) return []
  
  // 从 dataset.source 中提取字段
  const source = target.option.dataset.source
  if (Array.isArray(source) && source.length > 0) {
    return Object.keys(source[0]).map(key => ({
      label: key,
      value: key
    }))
  }
  return []
}

// 获取组件属性选项
const getPropertyOptions = (targetId: string) => {
  const target = chartEditStore.getComponentList.find(item => item.id === targetId)
  if (!target) return []
  
  const properties = []
  
  // 基础属性
  properties.push(
    { label: '标题', value: 'chartConfig.title' },
    { label: '宽度', value: 'attr.w' },
    { label: '高度', value: 'attr.h' },
    { label: 'X坐标', value: 'attr.x' },
    { label: 'Y坐标', value: 'attr.y' }
  )
  
  // 样式属性
  properties.push(
    { label: '透明度', value: 'styles.opacity' },
    { label: '亮度', value: 'styles.brightness' },
    { label: '对比度', value: 'styles.contrast' },
    { label: '饱和度', value: 'styles.saturate' }
  )
  
  // 图表配置属性
  if (target.option) {
    Object.keys(target.option).forEach(key => {
      if (typeof target.option[key] !== 'object') {
        properties.push({
          label: `图表配置.${key}`,
          value: `option.${key}`
        })
      }
    })
  }
  
  return properties
}

// 筛选条件选项
const filterConditionOptions = [
  { label: '等于', value: 'eq' },
  { label: '不等于', value: 'neq' },
  { label: '包含', value: 'includes' },
  { label: '大于', value: 'gt' },
  { label: '小于', value: 'lt' },
  { label: '大于等于', value: 'gte' },
  { label: '小于等于', value: 'lte' }
]

// 触发条件选项
const triggerConditionOptions = [
  { label: '等于', value: 'eq' },
  { label: '不等于', value: 'neq' },
  { label: '包含', value: 'includes' },
  { label: '大于', value: 'gt' },
  { label: '小于', value: 'lt' }
]

// 监听当前组件的数据变化，触发联动
watch(
  () => targetData.value.option,
  (newOption) => {
    handleLinkage(newOption)
  },
  { deep: true }
)

// 联动处理函数
function handleLinkage(currentOption: any) {
  linkageList.value.forEach(link => {
    const { 
      targetId, 
      filterField, 
      condition, 
      filterValue, 
      propertyPath, 
      propertyValue,
      triggerCondition,
      triggerValue 
    } = link
    
    if (!targetId) return
    
    // 检查触发条件
    const shouldTrigger = checkTriggerCondition(currentOption, triggerCondition, triggerValue)
    if (!shouldTrigger) return
    
    const target = chartEditStore.getComponentList.find(item => item.id === targetId)
    if (!target) return
    
    // 数据筛选联动
    if (linkageType.value === 'filter' && filterField && condition) {
      handleFilterLinkage(target, filterField, condition, filterValue)
    }
    
    // 组件属性联动
    if (linkageType.value === 'property' && propertyPath && propertyValue !== '') {
      handlePropertyLinkage(target, propertyPath, propertyValue)
    }
  })
}

// 检查触发条件
function checkTriggerCondition(currentOption: any, condition: string, value: string): boolean {
  // 这里以 inputValue 为例，实际可根据控件类型调整
  const currentValue = currentOption.inputValue || currentOption.value || ''
  
  switch (condition) {
    case 'eq':
      return currentValue == value
    case 'neq':
      return currentValue != value
    case 'includes':
      return String(currentValue).includes(value)
    case 'gt':
      return Number(currentValue) > Number(value)
    case 'lt':
      return Number(currentValue) < Number(value)
    default:
      return true
  }
}

// 处理数据筛选联动
function handleFilterLinkage(target: any, filterField: string, condition: string, filterValue: string) {
  if (!target.option?.dataset?.source) return
  
  const originalSource = target.option.dataset.source
  let filteredSource = [...originalSource]
  
  // 根据条件筛选数据
  switch (condition) {
    case 'eq':
      filteredSource = originalSource.filter((item: any) => item[filterField] == filterValue)
      break
    case 'neq':
      filteredSource = originalSource.filter((item: any) => item[filterField] != filterValue)
      break
    case 'includes':
      filteredSource = originalSource.filter((item: any) => 
        String(item[filterField]).includes(filterValue)
      )
      break
    case 'gt':
      filteredSource = originalSource.filter((item: any) => 
        Number(item[filterField]) > Number(filterValue)
      )
      break
    case 'lt':
      filteredSource = originalSource.filter((item: any) => 
        Number(item[filterField]) < Number(filterValue)
      )
      break
    case 'gte':
      filteredSource = originalSource.filter((item: any) => 
        Number(item[filterField]) >= Number(filterValue)
      )
      break
    case 'lte':
      filteredSource = originalSource.filter((item: any) => 
        Number(item[filterField]) <= Number(filterValue)
      )
      break
  }
  
  // 更新目标组件的数据
  target.option.dataset.source = filteredSource
}

// 处理组件属性联动
function handlePropertyLinkage(target: any, propertyPath: string, propertyValue: string) {
  const pathArray = propertyPath.split('.')
  let current = target
  
  // 遍历路径，找到目标属性
  for (let i = 0; i < pathArray.length - 1; i++) {
    if (current[pathArray[i]] === undefined) {
      current[pathArray[i]] = {}
    }
    current = current[pathArray[i]]
  }
  
  const lastKey = pathArray[pathArray.length - 1]
  
  // 尝试转换数据类型
  let finalValue: any = propertyValue
  if (!isNaN(Number(propertyValue))) {
    finalValue = Number(propertyValue)
  } else if (propertyValue === 'true' || propertyValue === 'false') {
    finalValue = propertyValue === 'true'
  }
  
  // 设置属性值
  current[lastKey] = finalValue
}
</script>

<style lang="scss" scoped>
.go-chart-linkage-setting {
  padding: 16px;
}
</style> 